package material

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// ProcessMaterialListAndTotal 获取并处理素材列表和总数
func (m *sMaterial) ProcessMaterialListAndTotal(ctx context.Context, in model.CommonListAndTotalInput, list interface{}, total *int) error {
	if in.Where == nil || g.IsNil(in.Where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.Material.Ctx(ctx).
		OmitEmpty().
		Where(in.Where).
		Page(in.Page, in.Size).
		Order(in.Sort).
		ScanAndCount(list, total, true)
}

// ProcessMaterialDetail 获取素材详情
func (m *sMaterial) ProcessMaterialDetail(ctx context.Context, where interface{}, detail interface{}) error {
	if where == nil || g.IsNil(where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.Material.Ctx(ctx).Where(where).Scan(detail)
}

// CheckMaterialExists 检测素材是否存在
func (m *sMaterial) CheckMaterialExists(ctx context.Context, where interface{}) (bool, error) {
	if where == nil || g.IsNil(where) {
		return false, gerror.New(`缺少请求参数`)
	}
	total, err := dao.Material.Ctx(ctx).
		Where(where).
		Count()
	if err != nil {
		return false, err
	}
	return total > 0, nil
}

// ProcessMaterialList 获取素材列表
func (m *sMaterial) ProcessMaterialList(ctx context.Context, where interface{}, list interface{}) error {
	if where == nil || g.IsNil(where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.Material.Ctx(ctx).Where(where).Scan(list)
}

// ProcessMaterialDetailById 根据素材ID获取素材详情
func (m *sMaterial) ProcessMaterialDetailById(ctx context.Context, materialId uint, detail interface{}) error {
	return m.ProcessMaterialDetail(
		ctx, g.Map{dao.Material.Columns().Id: materialId}, detail,
	)
}

// CheckMaterialExistsByAttachId 根据附件ID检测素材是否存在
func (m *sMaterial) CheckMaterialExistsByAttachId(ctx context.Context, attachId string) (bool, error) {
	return m.CheckMaterialExists(ctx, g.Map{dao.Material.Columns().AttachId: attachId})
}

// CheckMaterialExistsById 根据素材ID检测素材是否存在
func (m *sMaterial) CheckMaterialExistsById(ctx context.Context, materialId uint) (bool, error) {
	return m.CheckMaterialExists(ctx, g.Map{dao.Material.Columns().Id: materialId})
}

// ProcessMaterialMapById 通过素材ID处理并获取是素材MAP
func (m *sMaterial) ProcessMaterialMapById(ctx context.Context, materialId ...uint) (materialMap map[uint]model.MaterialBasicItem, err error) {
	if len(materialId) == 0 {
		return nil, gerror.New(`缺少素材ID`)
	}
	// 获取素材列表
	var materials []model.MaterialBasicItem
	err = m.ProcessMaterialList(ctx, g.Map{dao.Material.Columns().Id: materialId}, &materials)
	if err != nil {
		return nil, err
	}
	materialMap = make(map[uint]model.MaterialBasicItem)
	// 转换为Map
	for _, material := range materials {
		materialMap[material.Id] = material
	}
	return
}
